﻿using System;
using System.Collections.Generic;

namespace IceDog.Lib.Generic
{
    /// <summary>
    /// 带极坐标的矢量
    /// </summary>
    public class Vector : IComparable<Vector>
    {
        public Vector(double? r, double? theta)
        {
            if (r < 0)
            {
                r = -r;
                theta += 180;
            }
            this.R = r;
            this.Theta = theta % 360;
        }
        /// <summary>
        /// 幅度
        /// </summary>
        public double? R = null;
        /// <summary>
        /// 角度(单位:度)
        /// </summary>
        public double? Theta = null;
        /// <summary>
        /// 角度的弧度值
        /// </summary>
        public double? ThetaRadians
        {
            get { return Theta * Math.PI / 180; }
        }


        public static Vector operator +(Vector op1, Vector op2)
        {
            try
            {
                var newX = op1.R.Value * Math.Sin(op1.ThetaRadians.Value) +
                    op2.R.Value * Math.Sin(op2.ThetaRadians.Value);
                var newY = op1.R.Value * Math.Cos(op1.ThetaRadians.Value) +
                    op2.R.Value * Math.Cos(op2.ThetaRadians.Value);
                var newR = Math.Sqrt(newX * newX + newY * newY);
                var newTheta = Math.Atan2(newX, newY) * 180.0D / Math.PI;
                return new Vector(newR, newTheta);
            }
            catch
            {
                return new Vector(null, null);
            }
        }

        public static Vector operator -(Vector op1)
        {
            return new Vector(-op1.R, op1.Theta);
        }

        public static Vector operator -(Vector op1, Vector op2)
        {
            return op1 + (-op2);
        }

        public override string ToString()
        {
            var r = R.HasValue ? R.ToString() : "null";
            var theta = Theta.HasValue ? Theta.ToString() : "null";
            return "R:" + r + ",Theta:" + theta;
        }

        public int CompareTo(Vector other)
        {
            if (this.R > other.R)
            {
                return 1;
            }
            else if (this.R < other.R)
            {
                return -1;
            }
            return 0;
        }
        public class Comparer : IComparer<Vector>
        {
            public int Compare(Vector x, Vector y)
            {
                if (x.R > y.R)
                {
                    return 1;
                }
                else if (x.R < y.R)
                {
                    return -1;
                }
                return 0;
            }
            public static Comparer Default
            {
                get
                {
                    return new Comparer();
                }

            }
        }
    }
}
